package org.example.marshalling;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.example.entity.SubscribeReq;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>  </p>
 *
 * @author Chris
 * @since 2024/3/28 22:37
 */
public class SubReqClient {

    /**
     * 使用 slf4j 日志框架
     */
    private final static Logger log = LoggerFactory.getLogger(SubReqClient.class);

    public void connect(int port, String host) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            final Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) {
                            socketChannel.pipeline().addLast(MarshallingCodecFactory.buildMarshallingDecoder());
                            socketChannel.pipeline().addLast(MarshallingCodecFactory.buildMarshallingEncoder());
                            socketChannel.pipeline().addLast(new SubReqClientHandler());
                        }
                    });
            final ChannelFuture f = b.connect(host, port).sync();
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }

    private static class SubReqClientHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelActive(ChannelHandlerContext ctx) {
            for (int i = 0; i < 10; i++) {
                ctx.write(subReq(i));
            }
            ctx.flush();
        }

        private static SubscribeReq subReq(int i) {
            SubscribeReq builder = new SubscribeReq();
            builder.setSubReqID(i);
            builder.setUserName("Lilinfeng");
            builder.setProductName("Netty Book For Protobuf");

            List<String> address = new ArrayList<>();
            address.add("NanJing YuHuaTai");
            address.add("BeiJing LiuLiChang");
            address.add("ShenZhen HongShuLin");
            builder.setAddress(address);
            return builder;
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            log.info("Receive server response : [{}]", msg);
        }

        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) {
            ctx.flush();
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            log.error("error=", cause);
            ctx.close();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new SubReqClient().connect(8080, "127.0.0.1");
    }
}